package com.xy.ddd.core.config;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.xy.ddd.core.annotations.DomainService;
import com.xy.ddd.core.service.IDomainService;
import com.xy.ddd.core.utils.SpringContextUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Component
public class DomainRegistryFactory implements ApplicationContextAware {

    private static Map<String, IDomainService> domainServiceMap;

    private ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    @PostConstruct
    public void init() {

        Map<String, IDomainService> map = applicationContext.getBeansOfType(IDomainService.class);
        if (CollectionUtils.isEmpty(map)) {
            domainServiceMap = Maps.newHashMap();
            return ;
        }
        List<IDomainService> beans = new ArrayList<>(map.values());

        beans.stream().forEach(bean -> {
            DomainService annotation = bean.getClass().getAnnotation(DomainService.class);
            if (annotation != null) {
                domainServiceMap.put(annotation.code(), bean);
            } else {
                domainServiceMap.put(bean.getClass().getSimpleName(), bean);
            }
        });
    }

    public static IDomainService getDomainService(String code) {
        if (CollectionUtils.isEmpty(domainServiceMap)) {
            return null;
        }
        return domainServiceMap.get(code);
    }
}
